<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column type="index" :index="hIndex" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :total="total"
                :page-size="pagesize"
                :page-sizes="[1, 2, 3, 5,10]"
                :current-page="page"
                layout="sizes,prev,pager,next"
                @current-change="hCurrentChange"
                @size-change="hSizeChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑' : '添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
    <!-- 分配权限弹框 -->
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <AssignPermission
        ref="refAssign"
        :role-id="roleId"
        @close="showDialogAssign = false"
      />
    </el-dialog>
  </div>
</template>
<script>
import AssignPermission from './assignPermission.vue'
import { getRoles, delRole, addRole, editRole } from '@/api/settings'
export default {
  name: 'Settings',
  components: {
    AssignPermission
  },
  data() {
    return {
      page: 1,
      pagesize: 2,
      total: 0, // 总条数
      roles: [],
      // 表单
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      // 是否是编辑
      isEdit: false,
      // 分配权限显示弹框
      showDialogAssign: false,
      // 当前要分配权限角色的id
      roleId: ''
    }
  },
  // 计算属性
  computed: {
    hIndex() {
      console.log('当前页', (this.page - 1) * this.pagesize)
      return (this.page - 1) * this.pagesize + 1
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async loadRoles() {
      try {
        const res = await getRoles({ page: this.page, pagesize: this.pagesize })
        console.log('角色信息', res)
        this.total = res.data.total
        this.roles = res.data.rows
      } catch (err) {
        console.log(err)
      }
    },
    hCurrentChange(curPage) {
      console.log('curPage', curPage)
      // 更新页码
      this.page = curPage
      // 重发请求
      this.loadRoles()
    },
    hSizeChange(curPageSize) {
      console.log('curPageSize', curPageSize)
      // 更新一页条数
      this.pagesize = curPageSize
      this.page = 1
      // 重发请求
      this.loadRoles()
    },
    // 删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    async doDel(id) {
      try {
        // 删除
        await delRole(id)
        // 提示
        this.$message.success('删除成功')
        // 重新发送请求
        // 删除当前页最后一条数据
        if (this.roles.length === 1 && this.page > 1) {
          this.page--
        }
        this.loadRoles()
      } catch (err) {
        console.log(err)
      }
    },
    // 确定添加
    hSubmit() {
      // 表单校验
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 做添加
    async doAdd() {
      try {
        await addRole(this.roleForm)
        // 重新获取角色信息
        // 跳转到最后一页查看添加到数据
        // Math.ceil向上取整
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)

        this.loadRoles()
        // 提示成功
        this.$message.success('添加成功')
        // 关闭弹框
        this.showDialog = false
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    // 新增角色
    hAdd() {
      this.showDialog = true
      // 添加弹框
      this.isEdit = false
    },
    // 编辑
    hEdit(row) {
      this.showDialog = true
      // 数据回填
      this.roleForm = { ...row }
      // 编辑弹框
      this.isEdit = true
    },
    // 做编辑
    async doEdit() {
      try {
        await editRole(this.roleForm)
        // 重新获取角色信息
        this.loadRoles()
        // 提示成功
        this.$message.success('添加成功')
        // 关闭弹框
        this.showDialog = false
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    // 关闭弹框重置数据
    hClose() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },

    // 用户点击分配权限按钮
    hAssign(id) {
      // 显示弹框
      this.showDialogAssign = true
      // 保存id
      this.roleId = id

      // 通过refs来引用子组件，直接调用它的方法来发请求(同v-if)
      this.$nextTick(() => {
        this.$refs.refAssign.loadPermissionByRoleId()
      })
    }
  }
}
</script>
